﻿using System.Collections.Concurrent;

namespace HHFileViewServer
{
    /// <summary>
    /// 后台服务
    /// </summary>
    public class BackroundService : BackgroundService
    {
        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                // 配置信息
                var config = ServerOp.ServerConfig;
                // 文件夹
                DirectoryInfo dir = new DirectoryInfo(config.DownloadPath);
                // 文件夹下的所有文件夹
                DirectoryInfo[] directories = dir.GetDirectories();
                foreach (var item in directories)
                {
                    if ((DateTime.Now - item.CreationTime).TotalSeconds >= config.ClearConfig.RetentionTime)
                    {
                        // 删除子目录以及其下所有文件
                        item.Delete(true);
                    }
                }
                // 文件夹下面的所有文件
                FileInfo[] allFile = dir.GetFiles();
                foreach (var fileInfo in allFile)
                {
                    if ((DateTime.Now - fileInfo.CreationTime).TotalSeconds >= config.ClearConfig.RetentionTime)
                    {
                        // 删除文件
                        fileInfo.Delete();
                    }
                }
                await Task.Delay(config.ClearConfig.TaskInterval * 1000, stoppingToken);
            }
        }
    }
}
